import { Component, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { MessageService } from '@abp/message/message.service';
import {
    StorePutModelContentDto, StoreFunctionsServiceProxy, StorePutServiceProxy,
    PartsDeliveryServiceProxy,
    NewCertificateOutput,
    LabelCollectLong,
    LabelInformation,
    MaterialDetails,
    CancellingInput,
    WorkMatching,
    MatchingStoreInput,
    MatchingUpdateInput
} from '@shared/service-proxies/service-proxies';
import { TreeNode } from 'primeng/api';
import { BackWarehouseComponent } from '../back-warehouse/back-warehouse.component';

@Component({
    selector: 'app-return-warehouse',
    templateUrl: './return-warehouse.component.html',
    styleUrls: ['./return-warehouse.component.less']
})
export class ReturnWarehouseComponent extends AppComponentBase {
    //引入子组件
    @ViewChild('BackWarehouseComponent') BackWarehouseComponent: BackWarehouseComponent;
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() warehouseInfo: any;//仓库信息
    @Input() checktype: any
    lookforMatchingOutputList: LabelInformation = new LabelInformation();
    detailInfo: any;
    oldTable = [];
    title = undefined;
    saveInput = [];
    saving = false;
    active = false;
    releaseOrderOptions = [];
    showDetailListSelect: any = []
    qualifiedNumberOptions = [];
    selectRow: any = [];// 表格选中行
    treeTableSelect: any = []
    queryInfo = new StorePutModelContentDto();
    form = new NewCertificateOutput();
    inventoryPeopleList: LabelCollectLong[];
    lookDetailType: any;
    showDetailVisible: boolean;
    showDetailList: MaterialDetails[];
    operationPerson: any
    chooseFlag = undefined;//0 配套新增查看 1 配套新增选择 2配套修改查看 3 配套修改选择  4配套退库查看  5配套 退库选择 6配套退库记录查看
    chooseSon = [];
    rowData = {};
    reason: any
    operationTime: any = new Date()
    returnTitle: string;
    parentData: any;
    saveFlag = true;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _partsDeliveryServiceProxy: PartsDeliveryServiceProxy,
    ) {
        super(injector);
    }
    ngOnInit() {
        this.getInventoryPeopleListEv()
    }
    backToEx(data) {
        if (this.title != '退库查看' && this.title != '出库查看') {
            setTimeout(() => {
                if (data.parent != null) {
                    let flag = false;
                    for (const item of this.treeTableSelect) {
                        if (item.data.id == data.parent.node.data.id) {
                            flag = true;
                        }
                    }
                    if (!flag) {
                        this.treeTableSelect.push(data.parent.node);
                    }
                    // 匹对如果该工步已选择物料，要把之前的给覆盖而不是Push
                    if (this.saveInput.length != 0) {
                        for (let i = 0; i < this.saveInput.length; i++) {
                            let item = this.saveInput[i];
                            if (item.loadDetailsId == data.choose.loadDetailsId) {
                                item = data.choose
                            } else {
                                this.saveInput.push(data.choose);
                            }
                        }
                    } else {
                        this.saveInput.push(data.choose);
                    }
                }
                this.lookforMatchingOutputList.boundOutputs = data.table;
                // this.files1 = data.table;
            }, 5);
        }

    }
    // 展开
    expandAll(rs) {
        for (const node of rs) {
            this.TreeExpandRecursive(node, true);
        }
    }
    private TreeExpandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.TreeExpandRecursive(childNode, isExpand);
            });
        }
    }
    check(row) {
        this.chooseSon = [];
        if (this.treeTableSelect.length != 0) {
            for (const item of this.saveInput) {
                if (item.loadDetailsId == row.node.data.loadDetailsId) {
                    this.chooseSon = item.storeIdList;
                }
            }
        }
        if (this.returnTitle == '修改出库') {
            this.chooseFlag = 3;
            this.title = '选择出库';
        } else {
            this.chooseFlag = 2;
            this.title = '选择退库';
        }
        this.rowData = row;
        this.parentData = this.warehouseInfo.id;
        this.oldTable = this.lookforMatchingOutputList.boundOutputs;
        this.lookforMatchingOutputList.boundOutputs = [];
        //选择出库
        setTimeout(() => {
            this.BackWarehouseComponent.show();
        }, 5);
    }
    watch(row) {
        //查看
        this.rowData = row;
        if (this.returnTitle == '修改出库') {
            this.chooseFlag = 3;
            this.title = '出库查看';
        } else if (this.returnTitle == '退库查看') {
            this.chooseFlag = 6;
            this.title = '退库查看';
        } else {
            this.chooseFlag = 2;
            this.title = '退库查看';
        }
        this.parentData = this.warehouseInfo.id;
        setTimeout(() => {
            this.BackWarehouseComponent.show();
        }, 5);
    }
    // 弹窗隐藏
    displayclose() { }
    // 配套出库 查看的查看 
    lookDetail(item, type, operation) {
        this.lookDetailType = type
        this.detailInfo = item
        this._partsDeliveryServiceProxy.getMaterialDetails(
            this.warehouseInfo.id,
            item.id,
            item.loadDetailsId,
            operation
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.showDetailVisible = true
                this.showDetailList = result.materialDetails
            });
    }

    // 配套查看 /ProductionDesignAppService/
    lookforMatchingOutputEv(id) {
        this._partsDeliveryServiceProxy.lookforMatchingOutput(
            id
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.lookforMatchingOutputList = result
                abp.ui.clearBusy();
                this.expandAll(this.lookforMatchingOutputList.boundOutputs);
                this.treeTableSelect = this.lookforMatchingOutputList.checkOutputs
            });
    }
    lookEv(id) {
        this._partsDeliveryServiceProxy.stockReturnRecordMatchingOutput(
            id
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                abp.ui.clearBusy();
                this.lookforMatchingOutputList = result
                this.expandAll(this.lookforMatchingOutputList.boundOutputs);
                this.treeTableSelect = this.lookforMatchingOutputList.checkOutputs
                this.operationPerson = {label:result.cancellingUser,value:result.cancellingUserId};
                this.operationTime = result.cancellingTime;
            });
    }
    updateMatchingEv(input) {
        let info = new MatchingUpdateInput()
        info.id = this.warehouseInfo.id
        info.oldMatchings = input.matchings
        this._partsDeliveryServiceProxy.updateMatching(
            info
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this._messageService.success('修改成功')
                this.close()
            });
    }


    //退库人
    getInventoryPeopleListEv() {
        this._partsDeliveryServiceProxy.getInventoryPeopleList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.inventoryPeopleList = result
            });
    }




    // /PartsDeliveryAppService/CancellingHandle
    // 配套退库
    cancellingHandleEv(input) {
        let info = new CancellingInput()
        info.deliveryDocumentId = this.warehouseInfo.id
        info.cancellingReason = this.reason
        info.cancellingUser = this.operationPerson.label
        info.cancellingUserId = this.operationPerson.value
        info.matchings = input.matchings
        if (this.saveFlag) {
            this.saveFlag = false;
            this._partsDeliveryServiceProxy.cancellingHandle(
                info
            )
                .pipe(finalize(() => { }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this._messageService.success('退库成功')
                        this.close()
                        this.modalSave.emit();
                    } else {
                        this._messageService.error(result.message);
                    }
                });
        }
    }

    //打开弹窗
    onShown(): void {
        this.active = true;
        if (this.checktype == 2) {//修改
            this.returnTitle = "修改出库"
        } else if (this.checktype == 3) {//退库
            this.returnTitle = "退库作业"
        } else if (this.checktype == 4) {//退库查看
            this.returnTitle = "退库查看"
            this.lookEv(this.warehouseInfo.id);
            return
        }
        this.lookforMatchingOutputEv(this.warehouseInfo.id)

    }
    save() {
        let input = new MatchingStoreInput();
        input.matchings = [];
        for (let i = 0; i < this.treeTableSelect.length; i++) {
            let item = this.treeTableSelect[i];
            if (item.data.nodeLevel == 9) {
                this.treeTableSelect.splice(i, 1);
            }
        };
        let list2 = [];//配套过物料的工步
        let list3 = [];//没配套过物料的工步
        for (const parent of this.treeTableSelect) {
            let same = this.saveInput.filter(item => item.loadDetailsId == parent.data.loadDetailsId);
            if (same.length > 0) {
                list2.push(same[0]);
            }
        }
        list3 = this.treeTableSelect.filter(v => !list2.some((item) => item.loadDetailsId === v.data.loadDetailsId));
        input.matchings = list2;
        for (const item of list3) {
            let data = new WorkMatching();
            data.loadDetailsId = item.data.loadDetailsId;
            input.matchings.push(data);
        }
        if (this.checktype == 3) {
            this.cancellingHandleEv(input)
        } else {
            this.updateMatchingEv(input)
        }
    }
    //查看新增任务
    show(): void {
        abp.ui.setBusy();
        this.active = true;
        this.modal.show();
    }
    //关闭事件
    close(): void {
        //清空form表单
        this.lookforMatchingOutputList = new LabelInformation();
        this.treeTableSelect = [];
        this.operationPerson = undefined;
        this.operationTime = undefined;
        this.form = new NewCertificateOutput();
        this.selectRow = []
        this.active = false;
        this.modalSave.emit();
        this.modal.hide();
    }

}
